package com.lechuang.thread.config;

import com.lechuang.common.constant.BaseConstant;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

/**
 * 装饰MDC 内容传递
 */
public class MDCTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        String traceId = MDC.get(BaseConstant.TRACE_ID);
        // 对Runnable进行装饰，将主线程的MDC内容设置到子线程的MDC中
        return new Runnable() {
            @Override
            public void run() {
                try {
                    MDC.put(BaseConstant.TRACE_ID, traceId);
                    runnable.run();
                } finally {
                    MDC.clear();
                }
            }
        };
    }
}
